package network2;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Vector;

public class MultiChatClientThread extends Thread {
	MultiChatClient mcc;
	Socket socket;
	boolean tFlag = true;
	ObjectOutputStream send;
	ObjectInputStream receive;
	
	public MultiChatClientThread(MultiChatClient mcc, Socket s){
		this.mcc = mcc;
		this.socket = s;
	}
	public void run() {
		try{
			send = new ObjectOutputStream(socket.getOutputStream());
			receive = new ObjectInputStream(socket.getInputStream());

			SocketData sd = 
				new SocketData("login", 
								mcc.userID.getText(), 
								" 님이 로그인하였습니다.", 
								null);
			send.writeObject(sd);

			
			while(tFlag){
				sd = (SocketData)receive.readObject();
				mcc.dataSet(sd);
				
				if(sd.getCommand().equals("serverdown")){
					tFlag = false;
					send.writeObject(sd);
					
				// login을 전송한 후 서버는 userlist로 메시지를 재전송
				}else if(sd.getCommand().equals("userlist")){
					mcc.list.removeAll();
					mcc.clientList = (Vector)sd.getObj();
					mcc.list.setListData(mcc.clientList);
				
				}else if(sd.getCommand().equals("logout")){
					
					if(sd.getUser().equals(mcc.userID.getText())){// 내자신이 로그아웃
						tFlag=false;
						mcc.clientList.removeAllElements();
					}
					else{
						mcc.clientList.removeElement(sd.getUser());
					}
					mcc.list.setListData(mcc.clientList);
				}
			}
			
			receive.close();
			send.close();
			
			mcc.btnConnect.setEnabled(true);
			
			mcc.btnDisconnect.setEnabled(false);
			mcc.btnSend.setEnabled(false);
			
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}
	
	public void sendMsg(SocketData sd){
		try{
			send.writeObject(sd);
			send.flush();
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}
}
